import React, { useEffect, useState } from "react";
import ReactECharts from "echarts-for-react";
import dayjs from "dayjs";
import { message, Table } from "antd";
import { getYearlyQuestionCountUsingGet, getUserQuestionsByDateUsingGet } from "@/api/questionHistoryController";
import { useRouter } from "next/navigation";
import { ArrowLeftOutlined } from "@ant-design/icons";
import "./index.css";

interface Props {}

interface QuestionHistoryVO {
  question: API.Question;
  historyTime: string;
  count: number;
}

interface DailyQuestionCountVO {
  date: string;
  count: number;
}

/**
 * 刷题日历图
 * @param props
 * @constructor
 */
const CalendarChart = (props: Props) => {
  const {} = props;
  const router = useRouter();

  // 签到日期列表
  const [dataList, setDataList] = useState<DailyQuestionCountVO[]>([]);
  // 当前年份
  const year = new Date().getFullYear();
  // 是否显示题目列表
  const [showQuestionList, setShowQuestionList] = useState(false);
  // 当前选中的日期
  const [selectedDate, setSelectedDate] = useState<string>("");
  // 题目列表数据
  const [questionList, setQuestionList] = useState<QuestionHistoryVO[]>([]);

  // 请求后端获取数据
  const fetchDataList = async () => {
    try {
      const res = await getYearlyQuestionCountUsingGet({
        year,
      });
      if (res.data) {
        setDataList(res.data as unknown as DailyQuestionCountVO[]);
      }
    } catch (e: any) {
      message.error("获取刷题签到记录失败，" + e.message);
    }
  };

  // 保证只会调用一次
  useEffect(() => {
    fetchDataList();
  }, []);

  // 处理点击事件
  const handleClick = async (params: any) => {
    if (params.value) {
      try {
        // 从数据中获取日期
        const date = params.data[0];
        setSelectedDate(date);
        const res = await getUserQuestionsByDateUsingGet({
          date,
        });
        if (res.data) {
          setQuestionList(res.data as unknown as QuestionHistoryVO[]);
        }
        setShowQuestionList(true);
      } catch (e: any) {
        message.error("获取历史记录失败，" + e.message);
      }
    }
  };

  // 返回热力图
  const handleBack = () => {
    setShowQuestionList(false);
    setSelectedDate("");
    setQuestionList([]);
  };

  // 跳转到题目详情页
  const handleQuestionClick = (questionId: number) => {
    router.push(`/question/${questionId}`);
  };

  // 计算图表所需的数据
  const optionsData = dataList.map((item) => {
    return [item.date, item.count];
  });

  // 获取最大刷题数量
  const maxCount = Math.max(...dataList.map(item => item.count), 1);

  // 图表配置
  const options = {
    visualMap: {
      show: true,
      min: 0,
      max: maxCount,
      inRange: {
        // 颜色从浅绿色到深绿色
        color: ["#f0f9eb", "#e1f3d8", "#c2e7b0", "#95d475", "#67c23a"],
      },
      left: "right",
      top: "bottom",
      calculable: true,
    },
    calendar: {
      range: year,
      left: 20,
      // 单元格自动宽度，高度为 16 像素
      cellSize: [16, 16],
      yearLabel: {
        position: "top" as const,
        formatter: `${year} 年刷题记录`,
      },
    },
    series: {
      type: "heatmap" as const,
      coordinateSystem: "calendar" as const,
      data: optionsData,
    },
  };

  // 题目列表列配置
  const columns = [
    {
      title: "题目名称",
      dataIndex: ["question", "title"],
      key: "title",
      render: (text: string, record: QuestionHistoryVO) => (
        <a onClick={() => handleQuestionClick(record.question.id as number)}>
          {text}
        </a>
      ),
    },
    {
      title: "刷题时间",
      dataIndex: "historyTime",
      key: "historyTime",
      render: (text: string) => dayjs(text).format("YYYY-MM-DD HH:mm:ss"),
    },
    {
      title: "查看次数",
      dataIndex: "count",
      key: "count",
    },
  ];

  return (
    <div>
      {showQuestionList ? (
        <div>
          <div style={{ marginBottom: 16 }}>
            <a onClick={handleBack}>
              <ArrowLeftOutlined style={{ fontSize: 16 }} /> 返回
            </a>
            <div style={{ marginTop: 8 }}>
              日期：{selectedDate} 的刷题记录
            </div>
          </div>
          <Table
            columns={columns}
            dataSource={questionList}
            rowKey={(record) => record.question.id as number}
            pagination={false}
          />
        </div>
      ) : (
        <ReactECharts
          className="calendar-chart"
          option={options}
          onEvents={{
            click: handleClick,
          }}
        />
      )}
    </div>
  );
};

export default CalendarChart;